package com.fitso.model.dao.hibernate.type.nutrient;

import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;

import org.apache.commons.beanutils.BeanUtils;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;

import com.fitso.model.bean.measure.mass.MilliGram;
import com.fitso.model.bean.nutrition.Cholesterol;

/**
 * Conversion utility to/from the database/java type of {@link Cholesterol}
 * types
 * 
 * @author timothystorm
 */
public class CholesterolHibernateType extends NutrientHibernateType {
	public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException {
		BigDecimal mass = (BigDecimal) Hibernate.BIG_DECIMAL.nullSafeGet(rs, names[0]);
		return mass == null ? null : new Cholesterol(new MilliGram(mass));
	}

	public void nullSafeSet(PreparedStatement statement, Object value, int index) throws HibernateException,
			SQLException {
		if (value != null) {
			Cholesterol cholesterol = (Cholesterol) value;

			Hibernate.BIG_DECIMAL.nullSafeSet(statement, new MilliGram(cholesterol.getMass()).getValue(), index);
		} else {
			Hibernate.BIG_DECIMAL.nullSafeSet(statement, null, index);
		}

	}

	public Object replace(Object original, Object target, Object owner) throws HibernateException {
		try {
			Cholesterol copy = new Cholesterol();
			BeanUtils.copyProperties(copy, (Cholesterol) original);
			return copy;
		}
		catch (Exception e) {
			throw new HibernateException("failed to copy cholesterol", e);
		}
	}

	public Class<Cholesterol> returnedClass() {
		return Cholesterol.class;
	}

	public int[] sqlTypes() {
		return new int[] { Types.NUMERIC };
	}
}
